package com.shutuo.callnumtwofire;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import com.instwall.callbase.tool.LogUtil;
import com.instwall.callnumlistener.CallNumNotification;
import com.instwall.im.ImClient;
import com.instwall.im.ImListener;
import com.instwall.net.NetCoreException;
import com.shutuo.callnumtwofire.screeninfo.ScreenManager;
import com.shutuo.callnumtwofire.screeninfo.TwofireInfo;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
import ashy.earl.common.util.NetworkChangeHelper;
import ashy.earl.net.Callback;


public class TwoFireManager {

    private static TwoFireManager twoFireManager;


    private TwoFireManager(){
        //screenInfo changed
        ScreenManager.get().init();
        ScreenManager.ScreenListener screenListener = new ScreenManager.ScreenListener() {
            @Override
            public void onScreenInfoChanged(TwofireInfo info) {
                retryApi();
            }
        };
        ScreenManager.get().setScreenListener(screenListener);
        //network changed
        NetworkChangeHelper mNetwork = NetworkChangeHelper.get();
        NetworkChangeHelper.NetworkListener mNetworkListener = new NetworkChangeHelper.NetworkListener() {
            @Override
            public void onNetworkChanged(boolean hasActiveNetwork, String type, String name) {
                if (hasActiveNetwork) {
                    retryApi();
                }
            }
        };
        mNetwork.addNetworkListener(mNetworkListener);

        CallNumNotification.getCallNumNotification().addPlayerStateListener(playerStateListener);
    }
    private CallNumNotification.PlayerStateListener playerStateListener = new CallNumNotification.PlayerStateListener(){

        @Override
        public void onPlayerStateChanged() {
            Message message = Message.obtain();
            message.what = 1;

            mHandler.sendMessage(message);

        }
    };

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        //handleMessage为处理消息的方法
        public void handleMessage(@NotNull Message msg){
            super.handleMessage(msg);
            if (msg.what == 1) {
                retryApi();
            }
        }
    };

    public static TwoFireManager getInstance(){
        if(twoFireManager!=null) return twoFireManager;
        synchronized (TwoFireManager.class){
            twoFireManager = new TwoFireManager();
        }
        return twoFireManager;
    }


    public void init2DFireCallNum(){
        ImClient.get().addListener(iMHandler);
    }


    /**
     * IM 监听
     */
    private ImListener iMHandler = new ImListener(){

        @Override
        public void onStateChanged(int state){
            LogUtil.LogI(null,TFConfig.TAG+ " [onImStateChange] state:" + state);
        }

        @Override
        public void onNewMsg(@NonNull String from, @NonNull String msg){
            updateCallContent(ImClient.optServerCmdJson(msg));
        }


    };

    private void updateCallContent(JSONObject maybeParsedJson) {
        if (maybeParsedJson != null && TextUtils.equals(maybeParsedJson.optString("cmd", null), "erweihuo_queue_calling")) {
            LogUtil.LogI(null, TFConfig.TAG+ "[onNewMessage]    message:" + maybeParsedJson);
            if (maybeParsedJson != null) {
                String msg = constructMeiWeiJsParams(maybeParsedJson);
                CallNumData callNumData = new CallNumData(TFConfig.TYPE,msg);

//                CallNumNotification.getCallNumNotification().notificationClient(msg);
            }
        }
    }

    private String constructMeiWeiJsParams(JSONObject maybeParsedJson) {
        if (maybeParsedJson == null) {
            return null;
        }
        String oversize = maybeParsedJson.optString("4");
        String big = maybeParsedJson.optString("3");
        String in = maybeParsedJson.optString("2");
        String small = maybeParsedJson.optString("1");
        if (TextUtils.isEmpty(big)) big = "0";
        if (TextUtils.isEmpty(small)) small = "0";
        if (TextUtils.isEmpty(in)) in = "0";
        if (TextUtils.isEmpty(oversize)) oversize = "0";


        LogUtil.LogI(null,TFConfig.TAG+
                "constructJsParams: oversize : " + oversize + ",big : " + big + ",small : " + small + ",in : " + in);

        return "window.PushDataForFactory(\"{\\\"bigTable\\\":" + "\\\"" + big + "\\\"" +
                ",\\\"smallTable\\\":" + "\\\"" + small+ "\\\"" +
                ",\\\"factory\\\":" + "\\\"" + TFConfig.TYPE+ "\\\""+
                ",\\\"oversize\\\":" + "\\\"" + oversize + "\\\"" +
                ",\\\"inTable\\\":" + "\\\"" + in + "\\\"" +  "}\")";
    }

    private void retryApi(){
        Log.d(TFConfig.TAG, "retryApi ");
        TwofireInfo twofireInfo = ScreenManager.get().getTwofireInfo();
        if(twofireInfo==null)  return;
        long screenId = twofireInfo.screenId;
        long shop_id = twofireInfo.shop_id;
        if(screenId==0 || shop_id==0) return;
        final String json = "{\n" +
                "\t\"shop_id\": \""+shop_id+"\",\n" +
                "\t\"screen_id\": \""+screenId+"\"\n" +
                "}";
        TwoFireApi startApiTask = new TwoFireApi(json);
        startApiTask.makeRequest(new Callback<String, NetCoreException>() {
            @Override
            public void onResult(String rst, NetCoreException e) {
                Log.d(TFConfig.TAG, "onResult: e : "+e);
            }
        });
    }

    public void teardown(){

        CallNumNotification.getCallNumNotification().removePlayerStateListener(playerStateListener);
    }


}
